from datetime import datetime

from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger

from store.models import *
# Create your views here.
from dailyfresh.utils import *
from django.shortcuts import HttpResponse, redirect, render
from store.froms import *


def register(request):
    """注册"""
    if request.method == "GET":
        # 创建表单对象
        register_form = RegisterForm()
        return render(request, "bg/register.html", locals())
    else:
        # 创建表单对象
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            # 获取参数
            name = request.POST.get("name")

            # 查询所有
            seller1 = Seller.objects.filter(name=name).first()
            # 对用户名是否存在进行判断
            if seller1:
                a = "用户名已存在"
                return render(request, "bg/register.html", locals())

            password = request.POST.get("password")
            # 创建对象
            seller = Seller()
            # 赋值属性
            seller.name = name
            seller.password = encryption_md5(password)
            # 新增
            seller.save()
            # 重定向/响应
            return redirect("/bg/login")
        else:
            return render(request, "bg/register.html", locals())


def login(request):
    """登录"""
    if request.method == "GET":
        # 获取cookie
        name = request.COOKIES.get("name")
        return render(request, "bg/login.html", locals())
    else:
        # 创建表单对象
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            # 获取参数
            name = request.POST.get("name")
            password = request.POST.get("password")
            remember = request.POST.get("remember")
            # 查询
            seller = Seller.objects.filter(name=name, password=encryption_md5(password)).first()
            if seller:
                # 保存session
                request.session["logined"] = name

                # 设置对象
                response = redirect("/bg/index")
                # 判断是否单击记住我
                if remember == "1":
                    # 设置cookie
                    response.set_cookie("name", name, 60 * 60 * 24)
                else:
                    # 清除cookie
                    response.delete_cookie("name")
                return response
            else:
                return HttpResponse("登录失败")
        else:
            return render(request, "bg/login.html", locals())


@check_login
def index(request):
    return render(request, "bg/index.html")


@check_login
def loginout(request):
    # 清除session
    # request.session.clear()
    request.session.flush()
    return redirect("/bg/login")


@check_login
def store(request):
    # 获取当前登录用户的名字
    logined = request.session["logined"]
    seller = Seller.objects.filter(name=logined).first()
    if request.method == "GET":
        # 当前登录用户的店铺
        # django orm关联对象找不到会报错RelatedObjectDoesNotExist
        try:
            store = seller.store
        except:
            store = None
        return render(request, "bg/store.html", locals())
    else:
        # 获取参数
        data = request.POST
        store_id = data.get("store_id")
        name = data.get("name")
        address = data.get("address")
        description = data.get("description")
        picture = request.FILES.get("picture")  # 文件对象

        # 判断id
        if store_id:  # 修改
            # 查询对象
            store = Store.objects.get(id=store_id)
            if (datetime.now() - store.lasttime).days < 30:
                ab = "每月修改一次"
            return render(request, "bg/store.html", locals())
        else:  # 新增
            # 创建对象
            store = Store()

        # 属性
        store.name = name
        store.address = address
        store.description = description
        store.lasttime = datetime.now()

        # 判断picture
        if picture:
            store.picture = picture
        store.seller = seller

        # 新增/修改
        store.save()
        # 重定向/响应
        return redirect("/bg/store")


@check_login
def goods(request):
    """商品"""
    # 获取当前登录用户的名字
    logined = request.session["logined"]
    seller = Seller.objects.filter(name=logined).first()
    if request.method == "GET":
        # 获取变量search的元素
        search = request.GET.get("search")
        if search:
            #进行分页操作
            # 获取当前商品集合
            goods_list1 = seller.store.goods_set.filter(name__contains=search)
        else:
            # 获取当前商品集合
            goods_list1 = seller.store.goods_set.order_by("-id").all()
        # 设置每页显示的个数
        page_size = 3

        # 获取页码
        page = int(request.GET.get("page", 1))
        # 分页器对象,每页显示10条
        my_paginator = Paginator(goods_list1, page_size)
        # 当前页对象
        my_page = my_paginator.page(page)
        # 处理页码 前2 后2
        if page > 2:
            page_range = my_paginator.page_range[page - 3:page + 2]
        else:
            page_range = my_paginator.page_range[:5]

        # 处理编号，动态增加属性
        goods_list = my_page.object_list
        for index, goods in enumerate(goods_list):
            goods.index = (page - 1) * page_size + 1 + index  # python是动态语言，可以给对象增加/减少属性
        # 获取类型集合
        goodstypes_list = GoodsType.objects.all()
        return render(request, "bg/goods.html", locals())
    else:
        # 获取参数
        data = request.POST
        name = data.get("goods_name")
        goods_type_id = data.get("goods_type")
       # goodstype=GoodsType.objects.filter(name=goods_type).first()# 找到类型对象
       #  goodstypes_id=data.get("goodstypes_id")
        g_price = data.get("g_price")
        g_safe_date = data.get("g_safe_date")
        g_public_date = data.get("g_public_date")
        goods_number = data.get("goods_number")
        g_description = data.get("g_description")
        g_picture = request.FILES.get("g_picture")

        # 创建对象
        goods = Goods()

        # 属性
        goods.name = name
        goods.price = g_price
        goods.number = goods_number
        goods.description = g_description
        goods.shelfife = g_safe_date
        goods.producttime = g_public_date
        goods.picture = g_picture
        #goods.goodstype_id=goodstype.id#获取类型id
        goods.goodstype_id = goods_type_id
        goods.store_id=seller.store.id#获取商店id
        # 新增
        goods.save()
        # 重定向/响应
        return redirect("/bg/goods")

